<template lang="">
  <div class="home">
    <h1>list组件</h1>
    <!-- 头部 -->
    <Header @add="add"/>
    <!-- 主题内容 -->
    <Middle :list="list" @del="del"/>
    <!-- 底部 -->
    <Footer :list="list"/>
  </div>
</template>

<script>
import { nanoid } from "nanoid";
import  Header  from "../components/Header.vue";
import  Middle  from "../components/Middle.vue";
import  Footer  from "../components/Footer.vue";
export default {
  name: "HomeView",
  components: { Header, Middle, Footer },
  data() {
    return {
      list: []
    };
  },
  methods: {
    // 回车添加
    add(val) {
      var obj = { id: nanoid(), name: this.val, checked: false };
      this.list.unshift(obj);
      localStorage.setItem("list", JSON.stringify(this.list));
    },
    // 删除
    del(index) {
      this.list.splice(index, 1);
      localStorage.setItem("list", JSON.stringify(this.list));
    }
  },
  created() {
    var arr = JSON.parse(localStorage.getItem("list")) || [];
    this.list = arr;
  },
  watch: {
    list: {
      deep: true, //深度监听
      handler(newVal) {
        localStorage.setItem("list", JSON.stringify(newVal));
      }
    }
  }
};
</script>
